import axios from 'axios'
import { ElMessageBox, ElMessage } from 'element-plus'
import { getPlaid, getToken } from '@/utils/auth'
import qs from 'qs'

// create an axios instance
const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 1000000, // request timeout
  paramsSerializer: (params) => {
    console.log('params', params)
    params._ajax = 1
    params = qs.stringify(params, { indices: true })
    return params
  }
})
// request interceptor
service.interceptors.request.use(
  (config) => {
    // do something before request is sent
    const token = getToken()
    if (token) {
      config.headers['Access-Token'] = token
      config.headers['Addon-Name'] = import.meta.env.VITE_ADDON_NAME
      config.headers['Project-Type'] = 'addon'
      config.headers.Plaid = getPlaid()
    }
    return config
  },
  (error) => {
    // do something with request error
    console.log('error', error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  (response) => {
    const res = response.data
    const code = res.code
    switch (code) {
      case 0:
        return res
      case -1:
        ElMessage.error(res.msg)
        return Promise.reject(res)
      case -2:
        return Promise.reject(res)
      case 401:
        // 登录状态
        ElMessageBox.confirm('您已注销，可以取消以停留在此页面，或重新登录', '确认注销', {
          confirmButtonText: '重新登录',
          cancelButtonText: '关闭',
          type: 'warning'
        }).then(() => {
          // 清除本地存储的 token 并重新加载页面
          localStorage.removeItem('token')
          location.reload()
        })
        break
      default:
        return Promise.reject(response.data || { msg: '未知错误' })
    }
  },
  (error) => {
    console.log('error', error)
    ElMessage({
      message: error.message,
      type: 'error',
      duration: 10000
    })
    return Promise.reject(error)
  }
)

export default service
